package cn.ges.movie.controller.mobile

import cn.ges.base.sta.entity.user.BgUser
import cn.ges.base.sta.mapper.user.BgUserMapper
import cn.ges.base.sta.service.auth.BgUserService
import cn.ges.base.sta.vo.system.BgUserVO
import cn.ges.encryption.Md5PasswordUtil
import cn.ges.movie.vo.auth.MobileRegisterVO
import cn.ges.random.RandomUtil
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.ges.common.anno.DataBuryPoint
import com.ges.common.anno.ParameterCheck
import com.ges.common.dto.MsgDTO
import com.ges.common.service.auth.UserKeyInfoService
import com.ges.common.vo.ReturnJsonVO
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import javax.annotation.Resource

/**
 *
 * @author gespent@163.com
 * @date 2021/4/16 10:39
 */
@RestController
open class RegisterController {

    @Resource
    lateinit var bgUserMapper: BgUserMapper

    @Resource
    lateinit var userKeyInfoService: UserKeyInfoService

    @Resource
    lateinit var bgUserService: BgUserService


    @DataBuryPoint("帐号注册")
    @RequestMapping(value = ["/v1/auth/mobile/register"], method = [RequestMethod.POST])
    @ParameterCheck
    open fun mobileRegister(@RequestBody vo: MobileRegisterVO): ReturnJsonVO {
        QueryWrapper<BgUser>().apply {
            eq("mobile_num", vo.mobileNum!!)
        }.run {
            val selectOne = bgUserMapper.selectOne(this)
            if (selectOne != null) {
                return ReturnJsonVO.fail("该用户已经注册")
            }
        }
        vo.cast2Entity().apply {
            id = RandomUtil.getSequence()
            password = Md5PasswordUtil.getPassWord(vo.password!!, id.toString())
        }.run {
            if (bgUserMapper.insert(this) > 0) {
                return ReturnJsonVO.Companion.success(null, "注册成功")
            }
        }
        return ReturnJsonVO.fail("注册失败 请稍后再试")
    }

    private fun userNameAndPasswordLogin(vo: BgUserVO, ip: String): MsgDTO {
        val userByUserName = bgUserService.getUserByUserName(vo.userName!!) ?: return MsgDTO.fail("帐号或者密码错误")
        if (Md5PasswordUtil.getPassWord(vo.password!!, userByUserName.id.toString()) == userByUserName.password) {
            // 登录成功
            return userKeyInfoService.userLoginAndRefreshUserKeyInfo(userByUserName.id!!, userByUserName.allAuth!!, ip)
        }
        return MsgDTO.fail("帐号或者密码错误")
    }

}